package com.fhz.day007.sp

import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import com.fhz.day007.App
import com.fhz.day007.MainActivity
import java.lang.IllegalArgumentException
import kotlin.reflect.KProperty

/**
 * 时间:2021/10/21
 * @author msfeng
 * 简述: TODO
 */
object SPUtil {
    fun <T> operation(key:String,value:T ) = MySp(key,value)

}
//fun main(){
//    MySp<Int>().sp
//}

class MySp<T>(var key:String,var value: T){

    val sp:SharedPreferences by lazy {
        App.context.getSharedPreferences("user",Context.MODE_PRIVATE)
    }

    //取入到sp中
    operator fun getValue(mainActivity: MainActivity, property: KProperty<*>): T {
        var a = when(value){
            is String -> sp.getString(key,"moren")
            is Int -> sp.getInt(key,0)
            is Boolean -> sp.getBoolean(key,false)
            else -> throw IllegalArgumentException("参数错了")
        }
        return a as T
    }

    //从sp中放值
    operator fun setValue(mainActivity: MainActivity, property: KProperty<*>, any: T) {
        sp.edit{
            when(any){
                is String ->  putString(key,any)
                is Int -> putInt(key,any)
                is Boolean -> putBoolean(key,any)
            }
            apply()
        }
    }



}